package com.sc.service.serviceImpl;

import com.sc.common.pojo.PictureResult;
import com.sc.common.utils.FastDFSClient;
import com.sc.service.PictureService;
import org.csource.common.MyException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created by sc on 2017/10/11.
 */

@Service
public class PictureServiceImpl implements PictureService{

    @Value("${IMAGE_URL_PREFIX}")
    private String url_prefix;

    public PictureResult uploadPic(MultipartFile picfile){
        PictureResult pictureResult = new PictureResult();
        if(picfile.isEmpty()){
            pictureResult.setError(1);
            pictureResult.setMessage("没有上传图片");
            return pictureResult;
        }
        String filename = picfile.getOriginalFilename();
        String ext  = filename.substring(filename.indexOf(".")+1);
        try {
            FastDFSClient client = new FastDFSClient("classpath:properties/client.conf");
            String url = client.uploadFile(picfile.getBytes(),ext);
            pictureResult.setError(0);
            pictureResult.setUrl(url_prefix+url);
        } catch (IOException e) {
            pictureResult.setError(1);
            pictureResult.setMessage(e.getMessage());
            return pictureResult;
        } catch (MyException e) {
            pictureResult.setError(1);
            pictureResult.setMessage(e.getMessage());
            return pictureResult;
        }
        return pictureResult;
    }
}
